﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HengTong.Model.Db.Hr.Bill;
using HengTong.ViewModel.Person.SysPersonRepairBillVms;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TiaoTaoHelper.Models;
using TiaoTaoHelper.Wtm.Models;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Mvc;

namespace HengTong.Areas.Person.Controllers
{
    public partial class SysPersonRepairBillController
    {
        [ActionDescription("统计数据")]
        [HttpPost("GetStatistics")]
        public async Task<IActionResult> GetStatistics(StatisticsSearcher searcher)
        {
            if (ModelState.IsValid)
            {
                var vm = Wtm.CreateVM<SysPersonRepairBillVm>(passInit: true);
                var result = await vm.GetStatistics(searcher.Year, searcher.GroupId, searcher.OrgId);
                return Ok(result);
            }
            else
            {
                return BadRequest(ModelState.GetErrorJson());
            }
        }

        [HttpPost("UpdateWorkflowStatus")]
        [ActionDescription("更新工作流状态")]
        public async Task<ActionResult<Result<int>>> UpdateWorkflowStatus(string[] ids)
        {
            if (ids == null || !ids.Any())
            {
                return Ok(new Result<int>("请提供有效的ID"));
            }

            var transaction = await DC.Database.BeginTransactionAsync();

            try
            {
                var billIds = new List<Guid>();
                foreach (var id in ids)
                {
                    if (Guid.TryParse(id, out var billId))
                    {
                        billIds.Add(billId);
                    }
                }

                if (!billIds.Any())
                {
                    await transaction.RollbackAsync();
                    return Ok(new Result<int>("未找到有效的ID格式"));
                }

                var bills = await DC.Set<SysPersonRepairBill>()
                    .Where(x => billIds.Contains(x.ID))
                    .ToListAsync();

                if (!bills.Any())
                {
                    await transaction.RollbackAsync();
                    return Ok(new Result<int>("未找到对应的补录单据"));
                }

                // 预检查所有单据
                var problemBills = new List<string>();

                foreach (var bill in bills)
                {
                    // 检查是否已审批
                    if (bill.ApprovalTime == null)
                    {
                        problemBills.Add($"{bill.BillCode}: 尚未审批");
                        continue;
                    }

                    // 检查状态是否支持操作
                    if (bill.WorkflowStatus != WorkflowStatus.待提交 &&
                        bill.WorkflowStatus != WorkflowStatus.已取消)
                    {
                        problemBills.Add($"{bill.BillCode}: 当前状态'{bill.WorkflowStatus}'不支持此操作");
                        continue;
                    }
                }

                // 如果有问题的单据，直接返回错误
                if (problemBills.Any())
                {
                    await transaction.RollbackAsync();
                    return Ok(new Result<int>($"以下单据存在问题，无法更新工作流状态：\n{string.Join("\n", problemBills)}"));
                }

                var currentTime = DateTime.Now;
                var currentUser = Wtm.LoginUserInfo?.ITCode;
                var updateMessages = new List<string>();

                // 更新所有单据
                foreach (var bill in bills)
                {
                    string statusMessage;
                    switch (bill.WorkflowStatus)
                    {
                        case WorkflowStatus.待提交:
                            bill.WorkflowStatus = WorkflowStatus.审核中;
                            bill.BillStatus = BillStatus.正文;
                            statusMessage = $"{bill.BillCode}: 待提交 → 审核中";
                            break;

                        case WorkflowStatus.已取消:
                            bill.WorkflowStatus = WorkflowStatus.待提交;
                            bill.BillStatus = BillStatus.草稿;
                            statusMessage = $"{bill.BillCode}: 已取消 → 待提交";
                            break;

                        default:
                            continue;
                    }

                    bill.UpdateTime = currentTime;
                    bill.UpdateBy = currentUser;
                    updateMessages.Add(statusMessage);
                }

                await DC.SaveChangesAsync();
                await transaction.CommitAsync();

                return Ok(new Result<int>
                {
                    Data = bills.Count,
                    Message = $"成功更新 {bills.Count} 条记录：{string.Join("；", updateMessages)}"
                });
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync();
                return Ok(new Result<int>($"批量更新工作流状态失败：{ex.Message}"));
            }
            finally
            {
                await transaction.DisposeAsync();
            }
        }


        public class StatisticsSearcher
        {
            public int? Year { get; set; }

            public Guid? GroupId { get; set; }

            public Guid? OrgId { get; set; }
        }
    }
}